package cn.fl.custpay.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.KeyValueVO;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.custpay.service.ICmmWhiteListService;
import cn.fl.custpay.vo.CmmWhiteListVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.service.ISysUlFilesRecService;
import fl.constant.facade.framework.constant.DictionaryConstant;
import fl.customer.facade.customer.constant.CustomerConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.livecheck.condition.CmmWhiteListQC;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;

/**
 * @Description: 客户白名单 控制层
 */
@Controller
@RequestMapping("/custpay/cmmwhitelist")
public class CmmWhiteListController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CmmWhiteListController.class);

    /**
     * CmmWhiteList 服务层BEAN
     */
    @Autowired
    private ICmmWhiteListService cmmWhiteListService;
    /**
     * 数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    @Autowired
    private ISysUlFilesRecService sysUlFilesRecService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toListPage", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        ModelAndView view = new ModelAndView("custpay/cmmLiveChk/cmmWhiteListList");
        //证件类型
        String certTypCd = PropertiesCacheUtils.getProperty(DictionaryConstant.CODE_GRP_CERT_TYP_CD);
        List<KeyValueVO> list = this.sysDictionaryApiService.getKvList(certTypCd, CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());
        view.addObject("certTypCdList", list);
        List<KeyValueVO> liveList = this.sysDictionaryApiService.getKvList("LIVE0003", CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());
        view.addObject("busTypCdList", liveList);

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toListPage", "加载列表页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到新增修改页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载新增.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        ModelAndView view = new ModelAndView("custpay/cmmLiveChk/cmmWhiteListAdd");

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载新增.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载修改页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        ModelAndView view = new ModelAndView("custpay/cmmLiveChk/cmmWhiteListModify");
        view.addObject("id", id);

        String certTypCd = PropertiesCacheUtils.getProperty(DictionaryConstant.CODE_GRP_CERT_TYP_CD);
        List<KeyValueVO> list = this.sysDictionaryApiService.getKvList(certTypCd, CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());
        view.addObject("certTypCdList", list);
        List<KeyValueVO> liveList = this.sysDictionaryApiService.getKvList("LIVE0003", CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());
        view.addObject("busTypCdList", liveList);
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载修改.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到详情页面
     */
    @RequestMapping(value = "/toDetailPage.do", method = {RequestMethod.GET})
    public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toDetailPage", "加载例子详细页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        ModelAndView view = new ModelAndView("custpay/cmmLiveChk/cmmWhiteListDetail");
        view.addObject("id", id);

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toDetailPage", " 加载例子详细页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initList(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "initList", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String cstNm = request.getParameter("cstNmSearch");
        String certNo = request.getParameter("certNoSearch");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        CmmWhiteListQC qc = new CmmWhiteListQC();
        if (StringUtils.isNotEmpty(cstNm)) {
            qc.setCstNm(cstNm);
        }
        if (StringUtils.isNotEmpty(certNo)) {
            qc.setCertNo(certNo);
        }
        page.setCondition(qc);

        //TODO SOMETHING
        Pager pager = this.cmmWhiteListService.searchListPage(page);
        List<CmmWhiteListVO> list = (List<CmmWhiteListVO>) pager.getResultList();
        ListPageVO<CmmWhiteListVO> listPage = new ListPageVO<CmmWhiteListVO>(list, pager.getTotalCount());
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "initList", "加载列表页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return listPage;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "add", "新增活体白名单对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String cstNm = request.getParameter("cstNm");
        String certTypCd = request.getParameter("certTypCd");
        String certNo = request.getParameter("certNo");
        String startTime = request.getParameter("startTm");
        String endTime = request.getParameter("endTm");
        String remark = request.getParameter("remark");
        String listTypCd = request.getParameter("listTypCd");
        String mp = request.getParameter("mp");
        String busTypCd = request.getParameter("busTypCd");
        String liveChannelCd = request.getParameter("liveChannelCd");
        String bid = request.getParameter("bid");
        String pid = request.getParameter("pid");
        String times=request.getParameter("times");

        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
        CmmWhiteListVO entity = null;
        try {
            entity = new CmmWhiteListVO();
            entity.setCertNo(certNo);
            entity.setCertTypCd(certTypCd);
            entity.setCstNm(cstNm);
            entity.setStartTm(DateUtils.formatStringToDate(startTime, "yyyy-MM-dd HH:mm"));
            entity.setEndTm(DateUtils.formatStringToDate(endTime, "yyyy-MM-dd HH:mm"));
            entity.setRemark(remark);
            entity.setListTypCd(listTypCd);

            entity.setMp(mp);
            entity.setBusTypeCd(busTypCd);
            entity.setLiveChannelCd(liveChannelCd);
            entity.setpId(pid);
            entity.setbId(bid);
            entity.setAvailableTimes(Long.parseLong(times));


            //TODO ADD PARAM
            Long id = this.cmmWhiteListService.add(entity);
            BaseLogUtils.info(logger, "modify", "修改活体白名单上传附件开始");
            this.uploadAttchment(request,id);
            BaseLogUtils.info(logger, "modify", "修改活体白名单上传附件结束");
            result.setData(id);
            BaseLogUtils.info(logger, "add", "新增活体白名单数据.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "add", "新增活体白名单对象失败", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "add", "新增活体白名单对象失败.", CurrentThreadContext.getCurrentUserName(), ex);
        }
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "add", "新增活体白名单对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "modify", "修改活体白名单对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        String cstNm = request.getParameter("cstNm");
        String certTypCd = request.getParameter("certTypCd");
        String certNo = request.getParameter("certNo");
        String startTime = request.getParameter("startTm");
        String endTime = request.getParameter("endTm");
        String remark = request.getParameter("remark");
        String mp = request.getParameter("mp");
        String busTypCd = request.getParameter("busTypCd");
        String liveChannelCd = request.getParameter("liveChannelCd");
        String bid = request.getParameter("bid");
        String pid = request.getParameter("pid");
        String times=request.getParameter("times");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("数据不存在!");
            BaseLogUtils.info(logger, "modify", "修改活体白名单数据,主键不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        CmmWhiteListVO entity = null;
        try {
            entity = new CmmWhiteListVO();
            entity.setId(Long.valueOf(id));
            if (StringUtils.isNotEmpty(cstNm)) {
                entity.setCstNm(cstNm);
            }
            if (StringUtils.isNotEmpty(certTypCd)) {
                entity.setCertTypCd(certTypCd);
            }
            if (StringUtils.isNotEmpty(certNo)) {
                entity.setCertNo(certNo);
            }
            if (StringUtils.isNotEmpty(startTime)) {
                entity.setStartTm(DateUtils.formatStringToDate(startTime, "yyyy-MM-dd HH:mm"));
            }
            if (StringUtils.isNotEmpty(endTime)) {
                entity.setEndTm(DateUtils.formatStringToDate(endTime, "yyyy-MM-dd HH:mm"));
            }
            if (StringUtils.isNotEmpty(remark)) {
                entity.setRemark(remark);
            }

            if (StringUtils.isNotEmpty(mp)) {
                entity.setMp(mp);
            }
            if (StringUtils.isNotEmpty(busTypCd)) {
                entity.setBusTypeCd(busTypCd);
            }
            if (StringUtils.isNotEmpty(liveChannelCd)) {
                entity.setLiveChannelCd(liveChannelCd);
            }
            if (StringUtils.isNotEmpty(pid)) {
                entity.setpId(pid);
            }
            if (StringUtils.isNotEmpty(bid)) {
                entity.setbId(bid);
            }
            if(StringUtils.isNotEmpty(times)){
                entity.setAvailableTimes(Long.parseLong(times));
            }
            boolean success = this.cmmWhiteListService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("修改失败!");
                BaseLogUtils.info(logger, "modify", "修改活体白名单失败.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
            }else{
                BaseLogUtils.info(logger, "modify", "修改活体白名单上传附件开始");
                this.uploadAttchment(request,entity.getId());
                BaseLogUtils.info(logger, "modify", "修改活体白名单上传附件结束");
            }
            BaseLogUtils.info(logger, "modify", "修改活体白名单成功.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "modify", "修改活体白名单对象失败,id[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "modify", "修改活体白名单对象失败,id[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "modify", "修改活体白名单对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeById.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "remove", "移除对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("主键不能为空!");
            return result;
        }
        try {
            this.cmmWhiteListService.removeById(Long.valueOf(id));
            BaseLogUtils.info(logger, "removeById", "删除数据.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "remove", "移除对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "remove", "移除对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "remove", "移除对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "getById", "根据主键获取对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("主键不能为空!");
            BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            CmmWhiteListVO vo = this.cmmWhiteListService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("数据不存在!");
                BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getById", "获取数据.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "getById", "根据主键获取对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "getById", "根据主键获取对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "getById", "根据主键获取对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }


    /**
     * @MethodName uploadAttchment
     * @Description: 附件上传
     * @Author: wangpengtao@lionbridgecapital.cn
     * @CreateDate: 2020/2/21 9:57
     * @Version: V1.0.0
     * @Param request
     * @Param result
     * @Param id
     * @Return void
     * @UpdateRemark [序号][YYYY-MM-DD] [更改人姓名][变更描述]
     */
    private void uploadAttchment(HttpServletRequest request, Long id) {
        String attchmnt = request.getParameter("docArray");
        if (StringUtils.isNotEmpty(attchmnt)) {
            //上传解析
            try {
                String cfgOrgCd = PropertiesCacheUtils.getProperty(CustomerConstant.CST_BSCINFO_CFGORG);
                Boolean attchmntPass = this.sysUlFilesRecService.addAttchmnt(String.valueOf(id), attchmnt, "CWL001", "10", "CMM_WHITE_LIST", "白名单信息附件!", null, null, false, cfgOrgCd);
                if (null == attchmntPass || attchmntPass == false) {
                    throw new BaseException("附件上传失败");
                }
            } catch (Exception e) {
                BaseLogUtils.error(logger, "uploadAttchment", "-附件上传失败!", e);
                throw new BaseException(e.getMessage());
            }
        }
    }
}

